<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="重复执行" prop="reExecDelete">
        <el-select v-model="queryParams.reExecDelete" placeholder="请选择重复执行类型" clearable>
          <el-option
            v-for="dict in dict.type.data_resync_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:job:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['data:job:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['data:job:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="jobList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务id" align="center" prop="jobId" />
      <el-table-column label="任务名称" align="center" prop="jobName" />
      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="源数据源" align="center" prop="fromDatasource" />
      <el-table-column label="目标数据源" align="center" prop="toDatasource" />
      <el-table-column label="重复执行是否删除" align="center" prop="reExecDelete">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.data_resync_type" :value="scope.row.reExecDelete"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['data:job:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['data:job:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据同步任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="form.jobName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="时间配置" prop="timeConfig">
          <!-- <el-input v-model="form.timeConfig" placeholder="请输入时间配置" /> -->
          <testa @timeConfigJsonChanged="handleTimeConfigJsonChange" :innerTimeConfig="form.timeConfig"></testa>
        </el-form-item>
        <el-form-item label="源数据源" prop="fromDatasource">
          <!-- <el-input v-model="form.fromDatasource" placeholder="请输入源数据源id" /> -->
          <el-select v-model="form.fromDatasource" placeholder="请选择源数据源">
            <el-option
              v-for="datasource in datasourceList"
              :key="datasource.datasourceId"
              :label="datasource.datasourceName"
              :value="datasource.datasourceId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查询数据语句" prop="qurySql">
          <el-input v-model="form.qurySql" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="目标数据源id" prop="toDatasource">
          <!-- <el-input v-model="form.toDatasource" placeholder="请输入目标数据源id" /> -->
          <el-select v-model="form.toDatasource" placeholder="请选择目标数据源">
            <el-option
              v-for="datasource in datasourceList"
              :key="datasource.datasourceId"
              :label="datasource.datasourceName"
              :value="datasource.datasourceId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="插入数据语句" prop="insertSql">
          <el-input v-model="form.insertSql" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="manager">
              <el-select v-model="form.manager" placeholder="请选择任务负责人">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重复执行" prop="reExecDelete">
              <el-select v-model="form.reExecDelete" placeholder="请选择是否重复执行">
                <el-option
                  v-for="dict in dict.type.data_resync_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 根据重复输入的值展示删除语句输入框 -->
        <el-form-item label="删除语句" prop="deleteSql" v-if="form.reExecDelete == 1">
          <el-input v-model="form.deleteSql" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listJob, getJob, delJob, addJob, updateJob,updateStatus} from "@/api/data/job";
import { listUser } from "@/api/system/user";
import { listDatasource} from "@/api/data/datasource";
import timeConfig from "./timeConfig.vue";

export default {
  components: { testa: timeConfig },
  name: "Job",
  dicts: ['data_resync_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据同步任务表格数据
      jobList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jobName: null,
        reExecDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jobName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        fromDatasource: [
          { required: true, message: "源数据源不能为空", trigger: "blur" }
        ],
        qurySql: [
          { required: true, message: "查询数据语句不能为空", trigger: "blur"}
        ],
        toDatasource: [
          { required: true, message: "目标数据源不能为空", trigger: "blur" }
        ],
        insertSql: [
          { required: true, message: "插入数据语句不能为空", trigger: "blur"}
        ],
        reExecDelete: [
          { required: true, message: "重复执行不能为空", trigger: "blur"}
        ],
      },
      // 用户信息查询列表
      userList: [],
      // 数据源查询列表
      datasourceList: [],
    };
  },
  created() {
    this.getList();
    this.fetchUsertList();
    this.fetchDatasourceList();
  },
  methods: {
    /** 查询数据同步任务列表 */
    getList() {
      this.loading = true;
      listJob(this.queryParams).then(response => {
        this.jobList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jobId: null,
        sysJobId: null,
        jobName: null,
        fromDatasource: null,
        qurySql: null,
        toDatasource: null,
        insertSql: null,
        reExecDelete: null,
        deleteSql: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据同步任务";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      // console.log(row.status=== '0')
      // console.log(row)
      // 判断任务是否正在运行
      if(row.status=== "0"){
        //如果任务正在运行，则不允许修改
        this.$modal.msgError("运行中的任务禁止编辑，请先停止任务！");
      }else{
        //如果任务不在运行，则允许修改
        const jobId = row.jobId || this.ids
        await getJob(jobId).then(response => {
          this.form = response.data;
          this.title = "修改数据同步任务";
        })
        .catch(() => {})
        .finally(() => {
          this.open = true;
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.jobId != null) {
            updateJob(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addJob(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jobIds = row.jobId || this.ids;
      this.$modal.confirm('是否确认删除数据同步任务编号为"' + jobIds + '"的数据项？').then(function() {
        return delJob(jobIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('data/job/export', {
        ...this.queryParams
      }, `job_${new Date().getTime()}.xlsx`)
    },
    handleStatusChange(row){
      let text = row.status === '0' ? '启用' : '停用';
      this.$modal.confirm('确认要' + text + '此任务吗？').then(function() {
        return updateStatus(row.jobId);
      }).then(response => {
        if(response.code === 200){
          this.getList();
          this.$modal.msgSuccess(response.msg);
        }else{
          this.getList();
          this.$modal.msgError(response.msg);
        }
      });
    },
    fetchUsertList() {
      // 查询用户信息
      listUser().then(response => {
        this.userList = response.rows;
      });
    },
    //查询数据源
    fetchDatasourceList() {
      // 查询数据源
      listDatasource().then(response => {
        this.datasourceList = response.rows;
      });
    },
    // 时间配置json改变
    handleTimeConfigJsonChange(newTimeConfigJson) {
      // 将新的timeConfigJson赋值给form对象
      this.form.timeConfig = newTimeConfigJson;
    }
  }
};
</script>
